<template>
  <div class="medical-records-container">
    <div class="page-header">
      <h1>病情记录</h1>
      <div class="patient-selector">
        <span>当前患者：</span>
        <el-select 
          v-model="selectedPatientId" 
          filterable 
          placeholder="请选择患者" 
          @change="handlePatientChange"
          class="patient-select"
        >
          <el-option
            v-for="patient in patients"
            :key="patient.id"
            :label="patient.name + ' (ID: ' + patient.id + ')'"
            :value="patient.id"
          >
            <div class="patient-option">
              <div class="patient-option-info">
                <div>{{ patient.name }}</div>
                <div class="patient-option-id">ID: {{ patient.id }}</div>
              </div>
            </div>
          </el-option>
        </el-select>
      </div>
    </div>

    <div v-if="selectedPatient" class="patient-info-card">
      <el-card>
        <div class="patient-info-header">
          <div class="patient-basic-info">
            <h2>{{ selectedPatient.name }}</h2>
            <div class="patient-details">
              <span><el-icon><User /></el-icon> {{ selectedPatient.gender === 0 ? '男' : '女' }}, {{ selectedPatient.age }}岁</span>
              <span><el-icon><Phone /></el-icon> 联系方式: {{ selectedPatient.contact }}</span>
              <span><el-icon><Calendar /></el-icon> 入院日期: {{ formatDate(selectedPatient.admissionDate) }}</span>
              <el-tag :type="selectedPatient.patientStatus === 0 ? 'success' : 'danger'">
                {{ selectedPatient.patientStatus === 0 ? '正常' : '异常' }}
              </el-tag>
            </div>
          </div>
          <div class="patient-actions">
            <el-button type="primary" @click="handleAddRecord">
              <el-icon><Plus /></el-icon> 添加记录
            </el-button>
            <el-button @click="handlePrintRecords" v-if="conditionRecordsList.length > 0">
              <el-icon><Printer /></el-icon> 打印记录
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <div v-if="selectedPatient" class="medical-records-content">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="records-filter-card">
            <template #header>
              <div class="card-header">
                <span>筛选条件</span>
                <el-button type="primary" link @click="handleResetFilters">重置</el-button>
              </div>
            </template>
            
            <div class="filter-section">
              <h4>记录时间</h4>
              <el-date-picker
                v-model="filters.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%;"
              />
            </div>
            
            <div class="filter-section">
              <h4>关键词搜索</h4>
              <el-input
                v-model="filters.keyword"
                placeholder="输入关键词搜索"
                clearable
                @input="handleSearch"
              />
            </div>
            
            <el-button type="primary" class="apply-filter-btn" @click="handleApplyFilters">应用筛选</el-button>
          </el-card>
        </el-col>
        
        <el-col :span="18">
          <div class="records-header">
            <div class="records-title">病情记录列表</div>
            <div class="records-actions">
              <el-radio-group v-model="viewMode" size="small">
                <el-radio-button label="timeline">时间轴</el-radio-button>
                <el-radio-button label="table">表格</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          
          <!-- 时间轴视图 -->
          <div v-if="viewMode === 'timeline' && filteredRecords.length > 0" class="records-timeline">
            <el-timeline>
              <el-timeline-item
                v-for="record in filteredRecords"
                :key="record.id"
                :timestamp="formatDate(record.recordDate)"
                type="primary"
              >
                <el-card class="record-card">
                  <template #header>
                    <div class="record-header">
                      <div class="record-type">
                        <el-tag type="info">病情记录</el-tag>
                      </div>
                    </div>
                  </template>
                  <div class="record-content">
                    <div class="record-description">{{ record.conditionDescription }}</div>
                  </div>
                  <div class="record-actions">
                    <el-button size="small" @click="handleViewRecord(record)">查看详情</el-button>
                    <el-button size="small" type="primary" @click="handleEditRecord(record)">编辑</el-button>
                    <el-popconfirm
                      title="确定删除该记录吗？"
                      @confirm="handleDeleteRecord(record)"
                    >
                      <template #reference>
                        <el-button size="small" type="danger">删除</el-button>
                      </template>
                    </el-popconfirm>
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
          
          <!-- 表格视图 -->
          <div v-else-if="viewMode === 'table'" class="records-table">
            <el-table :data="filteredRecords" style="width: 100%" v-loading="loading">
              <el-table-column prop="id" label="编号" width="80" />
              <el-table-column prop="conditionDescription" label="病情描述" min-width="300" show-overflow-tooltip />
              <el-table-column label="记录日期" width="180">
                <template #default="scope">
                  {{ formatDate(scope.row.recordDate) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button size="small" @click="handleViewRecord(scope.row)">查看</el-button>
                  <el-button size="small" type="primary" @click="handleEditRecord(scope.row)">编辑</el-button>
                  <el-popconfirm
                    title="确定删除该记录吗？"
                    @confirm="handleDeleteRecord(scope.row)"
                  >
                    <template #reference>
                      <el-button size="small" type="danger">删除</el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 空数据状态 -->
          <div v-else class="empty-data">
            <el-empty description="暂无病情记录" />
            <el-button type="primary" @click="handleAddRecord">添加记录</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 记录编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
    >
      <el-form ref="recordFormRef" :model="recordForm" :rules="recordRules" label-width="100px">
        <el-form-item label="病情描述" prop="conditionDescription">
          <el-input 
            v-model="recordForm.conditionDescription" 
            type="textarea" 
            :rows="6" 
            placeholder="请输入病情描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRecordForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 记录详情对话框 -->
    <el-dialog
      title="病情记录详情"
      v-model="detailDialogVisible"
      width="500px"
      append-to-body
    >
      <div v-if="selectedRecord" class="record-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="记录编号">{{ selectedRecord.id }}</el-descriptions-item>
          <el-descriptions-item label="记录日期">{{ formatDate(selectedRecord.recordDate) }}</el-descriptions-item>
          <el-descriptions-item label="病情描述">{{ selectedRecord.conditionDescription }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEditRecord(selectedRecord)">编辑</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, 
  Edit, 
  Printer, 
  Calendar, 
  Phone,
  Plus
} from '@element-plus/icons-vue'
import { listPatients, getPatients } from '@/api/patients'
import { 
  listConditionrecords, 
  getConditionrecords,
  addConditionrecords, 
  updateConditionrecords, 
  delConditionrecords 
} from '@/api/conditionrecords'

const route = useRoute()
const router = useRouter()

// 患者数据
const patients = ref([])
const selectedPatientId = ref(null)
const selectedPatient = ref(null)
const loading = ref(false)

// 病情记录相关数据
const conditionRecordsList = ref([])

// 视图控制
const viewMode = ref('timeline')

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const detailDialogVisible = ref(false)
const selectedRecord = ref(null)

// 表单数据
const recordForm = reactive({
  id: null,
  patientId: null,
  conditionDescription: '',
  recordDate: null
})

// 表单验证规则
const recordRules = {
  conditionDescription: [{ required: true, message: '请输入病情描述', trigger: 'blur' }]
}

// 表单引用
const recordFormRef = ref(null)

// 筛选条件
const filters = reactive({
  dateRange: null,
  keyword: ''
})

// 过滤后的记录列表
const filteredRecords = computed(() => {
  let result = conditionRecordsList.value
  
  // 关键词筛选
  if (filters.keyword) {
    const keyword = filters.keyword.toLowerCase()
    result = result.filter(record => 
      record.conditionDescription.toLowerCase().includes(keyword)
    )
  }
  
  // 日期范围筛选
  if (filters.dateRange && filters.dateRange[0] && filters.dateRange[1]) {
    const startDate = new Date(filters.dateRange[0])
    const endDate = new Date(filters.dateRange[1])
    endDate.setHours(23, 59, 59, 999) // 设置为当天结束时间
    
    result = result.filter(record => {
      const recordDate = new Date(record.recordDate)
      return recordDate >= startDate && recordDate <= endDate
    })
  }
  
  return result
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取患者列表
const getPatientList = async () => {
  loading.value = true
  try {
    const response = await listPatients()
    patients.value = response
    
    // 如果URL中有patientId参数，则选中对应患者
    const patientId = route.query.patientId
    if (patientId) {
      selectedPatientId.value = parseInt(patientId)
      handlePatientChange(selectedPatientId.value)
    }
  } catch (error) {
    console.error('获取患者列表失败:', error)
    ElMessage.error('获取患者列表失败')
  } finally {
    loading.value = false
  }
}

// 处理患者选择变化
const handlePatientChange = async (patientId) => {
  if (!patientId) return
  
  loading.value = true
  try {
    // 获取患者详情
    const patientResponse = await getPatients(patientId)
    selectedPatient.value = patientResponse
    
    // 更新URL参数
    router.push({
      query: { ...route.query, patientId }
    })
    
    // 加载病情记录列表
    await loadConditionRecordsList(patientId)
    
  } catch (error) {
    console.error('获取患者详情失败:', error)
    ElMessage.error('获取患者详情失败')
  } finally {
    loading.value = false
  }
}

// 加载病情记录列表
const loadConditionRecordsList = async (patientId) => {
  try {
    const response = await listConditionrecords({ patientId })
    conditionRecordsList.value = response
  } catch (error) {
    console.error('获取病情记录失败:', error)
    ElMessage.error('获取病情记录失败')
  }
}

// 处理搜索
const handleSearch = () => {
  // 使用计算属性自动过滤
}

// 处理应用筛选
const handleApplyFilters = () => {
  // 使用计算属性自动过滤
}

// 处理重置筛选
const handleResetFilters = () => {
  filters.dateRange = null
  filters.keyword = ''
}

// 处理查看记录详情
const handleViewRecord = (record) => {
  selectedRecord.value = record
  detailDialogVisible.value = true
}

// 处理添加记录
const handleAddRecord = () => {
  if (!selectedPatient.value) {
    ElMessage.warning('请先选择患者')
    return
  }
  
  // 重置表单
  recordForm.id = null
  recordForm.patientId = selectedPatient.value.id
  recordForm.conditionDescription = ''
  recordForm.recordDate = null
  
  dialogTitle.value = '添加病情记录'
  dialogVisible.value = true
}

// 处理编辑记录
const handleEditRecord = (record) => {
  // 关闭详情对话框
  detailDialogVisible.value = false
  
  // 设置表单数据
  recordForm.id = record.id
  recordForm.patientId = record.patientId
  recordForm.conditionDescription = record.conditionDescription
  recordForm.recordDate = record.recordDate
  
  dialogTitle.value = '编辑病情记录'
  dialogVisible.value = true
}

// 处理删除记录
const handleDeleteRecord = async (record) => {
  try {
    await delConditionrecords(record.id)
    ElMessage.success('删除记录成功')
    
    // 重新加载记录列表
    await loadConditionRecordsList(selectedPatient.value.id)
  } catch (error) {
    console.error('删除记录失败:', error)
    ElMessage.error('删除记录失败')
  }
}

// 提交记录表单
const submitRecordForm = () => {
  recordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (recordForm.id) {
          // 编辑记录
          await updateConditionrecords(recordForm)
          ElMessage.success('更新记录成功')
        } else {
          // 添加记录
          await addConditionrecords(recordForm)
          ElMessage.success('添加记录成功')
        }
        
        dialogVisible.value = false
        
        // 重新加载记录列表
        await loadConditionRecordsList(selectedPatient.value.id)
      } catch (error) {
        console.error('保存记录失败:', error)
        ElMessage.error('保存记录失败')
      }
    }
  })
}

// 处理打印记录
const handlePrintRecords = () => {
  ElMessage.info('打印功能开发中...')
}

// 生命周期钩子
onMounted(() => {
  getPatientList()
})
</script>

<style scoped>
.medical-records-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.patient-selector {
  display: flex;
  align-items: center;
  gap: 10px;
}

.patient-select {
  width: 250px;
}

.patient-option {
  display: flex;
  align-items: center;
}

.patient-option-info {
  margin-left: 10px;
}

.patient-option-id {
  font-size: 12px;
  color: #909399;
}

.patient-info-card {
  margin-bottom: 20px;
}

.patient-info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.patient-basic-info {
  display: flex;
  flex-direction: column;
}

.patient-basic-info h2 {
  margin: 0 0 10px 0;
  font-size: 20px;
}

.patient-details {
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.patient-actions {
  display: flex;
  gap: 10px;
}

.medical-records-content {
  margin-top: 20px;
}

.records-filter-card {
  margin-bottom: 20px;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-section h4 {
  font-size: 14px;
  margin-bottom: 10px;
  color: #606266;
}

.apply-filter-btn {
  width: 100%;
  margin-top: 10px;
}

.records-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.records-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.record-card {
  margin-bottom: 10px;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-content {
  margin-bottom: 15px;
}

.record-description {
  white-space: pre-line;
}

.record-actions {
  display: flex;
  gap: 10px;
}

.empty-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.record-detail {
  padding: 10px;
}
</style> 